<template>
	<view class="xbc-editor">
		<!--输入区-->
		<view class="top flex-row">
			<view @tap="triggerAudio" class="icon flex-column">
				<text v-show="oper != 'audio'" class="iconfont icon-audio"></text>
				<text v-show="oper == 'audio'" class="iconfont icon-keyboard"></text>
			</view>
			<view class="block">
				<textarea
					@focus="onFocus"
					@blur="isFocus=false"
					v-model="content"
					class="textarea"
					:show-confirm-bar="false"
					:disabled="oper == 'audio'"
					:cursor-spacing="24"
					:maxlength="10000"
					:auto-blur="false"
					auto-height
					fixed />
				<xbc-audio @success="audioRecordSuccess" v-if="oper == 'audio'" />
			</view>
			<view class="button flex-row">
				<view @tap="trigger('emoji')" class="icon flex-column">
					<text class="iconfont icon-emoji"></text>
				</view>
				<view @tap="trigger('more')" v-show="!content" class="icon flex-column">
					<text class="iconfont icon-plus-circle"></text>
				</view>
				<view @tap="sendTextMessage" v-show="content" class="send flex-column">发送</view>
			</view>
		</view>
		<!--表情-->
		<xbc-emoji @select="selectEmoji" v-show="oper == 'emoji'" :show="!isFocus" />
		<!--更多-->
		<xbc-more @success="uploadSuccess" v-show="oper == 'more'" :show="!isFocus" />
	</view>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useEditor } from '@/hooks/useEditor'
import XbcMore from './components/more.vue'
import XbcAudio from './components/audio/index.vue'
import XbcEmoji from './components/emoji/index.vue'
import XBCIM from 'xbcim'

const emit = defineEmits(['change', 'send'])
const oper = ref('input')	// 当前操作：input-输入，audio-录音，emoji-表情，more-更多
const content = ref('')
const isFocus = ref(false)
const quoteMessage = ref(null)
const mentionMembers = ref([])
const placeholderHeight = ref('60px')
const { scrollToBottom, getFootHeight } = useEditor()

// 发送文本消息
function sendTextMessage() {
  try {
    // 组合文本消息体
    const { targetId, type } = uni.getStorageSync('currentConversation')
    const message = XBCIM.createTextMessage({
		target: targetId,
		content: content.value,
		conversationType: type,
		quote: quoteMessage.value,
		at: mentionMembers.value,
		id: new Date().getTime(),
	})
	
	// 组合前端显示消息
	const { user } = XBCIM.getAppData()
	emit('send', {
		...message,
		content: JSON.stringify(message.content),
		senderId: user.userId,
		senderName: user.name,
		senderAvatar: user.avatar
	})
	
	// 发送消息
	sendMessage(message)
  } catch (error) {
    console.error(error)
  }
}

// 发送消息
function sendMessage(message: any) {
  XBCIM.sendMessage(message).then(() => {}).catch(error => {
	  uni.showToast({
	  	icon: 'none',
		title: error.msg
	  })
  })
  content.value = ''
  quoteMessage.value = null
  mentionMembers.value = []
}

// 切换
function trigger(op: string) {
	setTimeout(() => {
		oper.value = op
		getFootHeight(placeholderHeight)
	}, 100)
}

// 上传成功
function uploadSuccess({ type, data }) {
	let message: any
	const id: number = new Date().getTime()
	const { targetId, type: conversationType } = uni.getStorageSync('currentConversation')
	
	switch (type){
		case 'file':
			message = XBCIM.createFileMessage({
				id,
				quote: JSON.parse(quoteMessage.value),
				at: mentionMembers.value,
				conversationType,
				target: targetId,
				name: '这是一个测试文档',
				size: 227161,
				url: data.url,
			})
			break
		case 'image':
			message = XBCIM.createImageMessage({
				id,
				quote: JSON.parse(quoteMessage.value),
				at: mentionMembers.value,
				conversationType,
				target: targetId,
				url: data.url,
			})
			break
		case 'video':
			message = XBCIM.createVideoMessage({
				id,
				quote: JSON.parse(quoteMessage.value),
				at: mentionMembers.value,
				conversationType,
				coverUrl: 'https://cdn.xiangbaicheng.com/public/media/mov.jpg',
				duration: '00:00:10.03',
				target: targetId,
				size: 788493,
				width: 320,
				height: 176,
				url: data.url,
			})
			break
		case 'location':
			message = XBCIM.createLocationMessage({
				id,
				quote: JSON.parse(quoteMessage.value),
				at: mentionMembers.value,
				conversationType,
				target: targetId,
				name: data.name,
				address: data.address,
				latitude: data.latitude,
				longitude: data.longitude,
			})
			break
		case 'card':
			message = XBCIM.createCardMessage({
				id,
				quote: JSON.parse(quoteMessage.value),
				at: mentionMembers.value,
				conversationType,
				target: targetId,
				...data
			})
			break
	}
	
	sendMessage(message)
	reset()
}

// 音频录制成功
function audioRecordSuccess({ duration, url }) {
	const { targetId, type } = uni.getStorageSync('currentConversation')
	const message = XBCIM.createAudioMessage({
		id: new Date().getTime(),
		quote: JSON.parse(quoteMessage.value),
		at: mentionMembers.value,
		conversationType: type,
		target: targetId,
		duration,
		url
	})
	sendMessage(message)
}

// 切换语音
function triggerAudio() {
	oper.value = oper.value == 'audio' ? 'input' : 'audio'
	getFootHeight(placeholderHeight)
}

// 选择表情
function selectEmoji(emoji: string) {
	content.value += emoji
}

// 就聚焦
function onFocus() {
	isFocus.value = true
	// #ifdef H5
	oper.value = 'input'
	// #endif
}

// 重置
function reset(isBottom: Boolean = true) {
	if(oper.value != 'audio'){
		oper.value = 'input'
		getFootHeight(placeholderHeight, isBottom)
	}
}

// #ifndef H5
uni.onKeyboardHeightChange(({ height }) => {
	if(!height) reset()
})
// #endif

watch(placeholderHeight, height => {
	emit('change', height)
})

defineExpose({
	reset
})
</script>

<style lang="scss" scoped>
.xbc-editor {
	width: 100%;
	background-color: #f5f5f5;
	border-top: 2rpx solid #eee;
	transition: height 0.3s ease;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 999;
	
	::-webkit-scrollbar {
		display: none;
	}
	
	.top {
		padding: 20rpx 10rpx;
		align-items: flex-end;
		
		.send {
			color: #fff;
			width: 100rpx;
			height: 64rpx;
			margin: 0 10rpx;
			font-size: 28rpx;
			border-radius: 10rpx;
			background-color: #2BA245;
		}
		
		.block {
			flex: 1;
			margin: 0 10rpx;
			padding: 0 20rpx;
			overflow: hidden;
			min-height: 76rpx;
			border-radius: 10rpx;
			background-color: #fff;
			position: relative;
		}
		
		.textarea {
			width: 100%;
			color: #333;
			font-size: 30rpx;
			max-height: 160px;
			padding-top: 20rpx;
			padding-bottom: 12rpx;
			background-color: #fff;
		}
		
		.icon {
			@include fullsize(80rpx);
			
			.iconfont {
				font-size: 60rpx;
				
				&.icon-emoji {
					font-size: 58rpx;
				}
			}
		}
	}
}

</style>